<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { DefResourceModel } from '#/api';
import type { RequestEnum } from '#/enums/httpEnum';

import { onMounted, ref, watch } from 'vue';

import { useFs } from '@fast-crud/fast-crud';
import { Popover, Tag } from 'ant-design-vue';
import { cloneDeep, uniqueId } from 'lodash-es';

import { HTTP_TAG_MAP } from '#/enums/httpEnum';

import { createCrudOptions } from '../data/api-crud';
import ApiSelectModal from './api-select-modal.vue';

defineOptions({
  name: '资源接口',
  inheritAttrs: false,
});

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  mode: 'view',
});
const emit = defineEmits<Emits>();
interface Props {
  modelValue?: DefResourceModel.DefResourceApiVO[];
  mode: string;
}
interface Emits {
  (e: 'update:modelValue', value: Recordable[]): void;
}
const apiSelectRef = ref();
const { crudRef, crudBinding, crudExpose } = useFs({
  createCrudOptions,
  context: { emit, apiSelectRef, mode: props.mode },
});

// 页面打开后获取列表数据
onMounted(async () => {
  watch(
    () => {
      return props.modelValue;
    },
    (value: DefResourceModel.DefResourceApiVO[]) => {
      const list = value ? cloneDeep(value) : [];

      list.forEach((v) => (v.tempId = uniqueId()));

      crudBinding.value.data = list;
    },
    {
      immediate: true,
    },
  );
});

function handleSuccess(list: Recordable[]) {
  emit('update:modelValue', list);
  crudExpose.setTableData(list);
}

const getType = (requestMethod: RequestEnum) => {
  return HTTP_TAG_MAP.get(requestMethod) || 'default';
};
</script>

<template>
  <div class="resource-api">
    <FsCrud ref="crudRef" v-bind="crudBinding">
      <template #cell_uri="scope">
        <Popover>
          <Tag :color="getType(scope.form.requestMethod)">
            {{ scope.form.requestMethod }}
          </Tag>
          {{ scope.form.uri }}
          <template #content>
            服务： {{ scope.form.springApplicationName }}
            <br />
            名称：{{ scope.form.controller }}
            <br />
            接口名：{{ scope.form.name }}
            <br />
            地址： {{ scope.form.uri }}
            <br />
            请求方式： {{ scope.form.requestMethod }}
            <br />
          </template>
        </Popover>
      </template>
    </FsCrud>
    <ApiSelectModal ref="apiSelectRef" @success="handleSuccess" />
  </div>
</template>
<style lang="scss" scoped>
.fs-crud-container {
  .fs-crud-footer {
    display: none;
  }
}
</style>
